<?php
/**
 * Created by PhpStorm.
 * User: ari
 * Date: 11/19/14
 * Time: 11:30 AM
 */
namespace BC\User\Commands;

use BC\PGP\Commands\PGPImportPublicKeyCommand;
use BC\PGP\Commands\PGPSearchCommand;
use BC\PGP\PGPConfig;
use BC\PGP\PublicKey;
use BC\User\Exceptions\UserAlreadyExistsException;
use CPath\Data\Map\IKeyMapper;
use CPath\Request\IRequest;
use CPath\Request\Validation\IValidation;

class ImportUser extends PGPImportPublicKeyCommand
{
	/** @var IValidation[] */
	private $mValidations = array();
	private $mPublicKey;
	function __construct($armoredPublicKey) {
		$this->mPublicKey = $armoredPublicKey;
		parent::__construct($armoredPublicKey);
		$this->setPrimaryKeyRing(PGPConfig::$KEYRING_USER);
	}

	function addUserIDValidation(IValidation $Validation, IValidation $_Validation=null) {
		foreach(func_get_args() as $Validation)
			$this->mValidations[] = $Validation;
	}

	/**
	 * Execute a command and return a response. Does not render
	 * @param IRequest $Request
	 * @param null $armoredPublicKey
	 * @throws \BC\User\Exceptions\UserAlreadyExistsException
	 * @return ImportUser
	 */
	function execute(IRequest $Request) {
		$PublicKey = new PublicKey($this->mPublicKey);
		$userID = $PublicKey->getUserID();
		$userEmail = $PublicKey->getUserIDEmail();

		/** @var IValidation $Validation*/
		foreach($this->mValidations as $Validation)
			$Validation->validate($Request, $userID);

		$UserSearch = new PGPSearchCommand($userID, '=');
		$UserSearch->addKeyRing(PGPConfig::$KEYRING_USER);
		//$UserSearch = $UserSearch->queryOne();
		$UserSearch->executeWithCallback($Request, function(PGPSearchCommand $User) use ($userID, $userEmail) {
			if($User->getUserID() === $userID)
				throw new UserAlreadyExistsException("User '" . $userID . "' already exists. Please choose a different user name");
			if($User->getUserID() === $userEmail)
				throw new UserAlreadyExistsException("User '" . $userEmail . "' already exists. Please choose a different user name");
			if($userEmail && $User->getEmail() === $userEmail)
				throw new UserAlreadyExistsException("User email '" . $userEmail . "' already exists. Please choose a different email address");
		});
return  parent::execute($Request);
	}

	function queryUser(IRequest $Request) {
		$UserSearch = new PGPSearchCommand($this->getKeyID(), '');
		$UserSearch->addKeyRing(PGPConfig::$KEYRING_USER);
		return $UserSearch->queryOne($Request);
	}

	/**
	 * Map data to the key map
	 * @param IKeyMapper $Map the map inst to add data to
	 * @internal param \CPath\Request\IRequest $Request
	 * @internal param \CPath\Request\IRequest $Request
	 * @return void
	 */
	function mapKeys(IKeyMapper $Map) {
		parent::mapKeys($Map);
//		if($this->getFingerprint())
//			$Map->map('user', $this->getUser());
	}

}

